package de.pa2.templates;

import java.io.File;
import java.io.StringWriter;
import java.util.Hashtable;
import java.util.Map;

import org.apache.commons.lang.StringEscapeUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;

public class VelocityTool {
	private Hashtable<String, Object> context = new Hashtable<String, Object>();
	private String basedir = null;

	public Map<String, Object> getContext() {
		return context;
	}

	public void add(String key, Object o) {
		if (context.containsKey(key))
			context.remove(key);
		context.put(key, o);
	}

	public VelocityTool(String template) {
		File tpl = new File(template);
		basedir = tpl.getParent();
	}

	public String include(String tmp) throws ResourceNotFoundException,
			ParseErrorException, Exception {
		String template = basedir + "/" + tmp;// + ".vm";
		Template tpl = VelocityHelper.getEngine().getTemplate(template);
		StringWriter writer = new StringWriter();
		VelocityContext ctx = new VelocityContext();
		VelocityTool tool = new VelocityTool(template);
		for (String key : context.keySet()) {
			tool.add(key, context.get(key));
			ctx.put(key, context.get(key));
		}
		ctx.put("tool", tool);
		tpl.merge(ctx, writer);
		return writer.getBuffer().toString();
	}

	public String escapeHtml(String text) {
		if (text == null)
			throw new IllegalArgumentException("text must not be null");
		return StringEscapeUtils.escapeHtml(text);
	}

	public boolean isset(Object o) {
		if (o == null) {
			return false;
		} else if (o instanceof String) {
			return !"".equals(o);
		} else if (o.getClass().isArray()) {
			Object[] array = (Object[]) o;
			return array.length > 0;
		} else {
			return true;
		}
	}
	
	public String toLowerCase(String str)
	{
		return str.toLowerCase();
	}
}
